<template>
  <div>
    <el-dialog width="80%" title="sku列表" :visible.sync="dialogVisible" @close="closeModal">

      <el-row
        style="margin-top:20px;margin-bottom:10px;"
        :gutter="20"
        type="flex"
        justify="end"
      >
        <el-col :span="2" :offset="0">
          <el-button type="primary" size="small" @click="addOneSku">新增</el-button>
        </el-col>
      </el-row>

      <el-table :data="skuList" border stripe>

        <el-table-column
          label="#"
          width="70"
          align="center"
          type="index"
          fixed="left"
        />

        <el-table-column
          label="图片"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <el-upload
              :ref="'upload'+scope.row.id"
              class="avatar-uploader"
              :action="uploadImageUrl"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="token"
              :show-file-list="false"
              @click.native="handleRef(scope.row.id)"
            >
              <img v-if="scope.row.pic" style="display:block;width:100px;height:100px;" :src="scope.row.pic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </template>
        </el-table-column>

        <el-table-column
          v-for="item in sku"
          :key="item.name"
          align="center"
          :label="item.name"
          width="180"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row[item.type]" :placeholder="item.name" size="mini" />
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="库存"
          width="170"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.stock" placeholder="库存" size="mini" />
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="预警库存"
          width="170"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.lowStock" placeholder="预警库存" size="mini" />
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="锁定库存"
          width="170"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.lockStock" placeholder="锁定库存" size="mini" />
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="价格"
          width="170"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" placeholder="价格" size="mini" />
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="销量"
          width="170"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.sale" placeholder="销量" size="mini" />
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="170"
        >
          <template slot-scope="scope">
            <el-button style="color:red;" type="text" size="mini" @click="deleteSku(scope.row.id,scope.row.productId)">删除</el-button>
            <el-button type="text" size="mini" @click="updateSkuItem(scope.row.id)">{{ scope.row.productId?'修改编辑':'保存' }}</el-button>
          </template>
        </el-table-column>

      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleUpdateSku">取 消</el-button>
        <!-- <el-button type="primary" @click="saveSku">确 定</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSkusByProductId as getSkusByProductIdAPi,
  delSku as delSkuApi,
  addProductSkus as addProductSkusApi,
  updateSkuInfo as updateSkuInfoApi

} from '@/api/product/list'
import Vue from 'vue'
import mix from '@/mixin'
import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'UpdateSku',
  mixins: [mix],
  data() {
    return {
      productId: '',
      dialogVisible: false, // 对话框打开状态
      skuList: [], // skuList
      // sku: [
      //   {
      //     type: 'color',
      //     name: '颜色',
      //     example: '土豪金',
      //     input: '',
      //     selectedArr: [],
      //     arr: []
      //   },
      //   {
      //     type: 'size',
      //     name: '大小',
      //     input: '',
      //     example: '128g',
      //     selectedArr: [],
      //     arr: []
      //   }
      // ],
      uploadRefId: '',
      ifupdate: true// true为更新，false为新增
    }
  },
  created() {

  },
  methods: {

    // 新增一个sku
    addOneSku() {
      var obj = {
        'id': uuidv4(), // 如果是新增 不需要
        'lockStock': 0, // 锁定库存
        'lowStock': 0, // 库存警戒线
        'pic': '', // 图片
        'price': 0, // 当前价格
        'productId': '', // 商品的id,如果是新增,不需要
        'promotionPrice': 0, // 单品促销价格
        'sale': 0, // 销量
        'skuCode': '', // sku的编码,手动填写
        // spData:  [{"key":"颜色","value":"蓝色"},{"key":"容量","value":"32G"}]
        'spData': '', // sku属性，json格式String类型 ,
        'stock': 0 // 库存
      }
      Vue.set(this.skuList, this.skuList.length, obj)
    },
    // 更新一个sku
    updateSkuItem(id) {
      var item = this.skuList.find(ele => ele.id === id)
      // sku格式化
      item.spData = []
      for (let i = 0; i < this.sku.length; i++) {
        var key = this.sku[i].type
        var name = this.sku[i].name
        item.spData.push({ key: name, value: item[key] })
      }
      item.spData = JSON.stringify(item.spData)
      console.log(item)
      var api = null
      if (item.productId) {
        // 修改sku
        api = updateSkuInfoApi
        this.ifupdate = true
      } else { // 新增sku
        api = addProductSkusApi
        delete item.id
        item.productId = this.productId
        this.ifupdate = false
      }
      api(item)
        .then(res => {
          const { message, success } = res
          if (success) {
            if (this.ifupdate) {
              this.$message.success('更新sku成功!')
            } else {
              this.$message.success('新增sku成功!')
            }
            this.getSkuList()
          } else {
            this.$message.error(message)
          }
        })
    },
    // 删除一个sku项目
    deleteSku(id, productId) {
      this.$confirm('是否删除sku?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (!productId) {
          this.skuList.pop()
          return
        }
        delSkuApi(id)
          .then(res => {
            const { message, success } = res
            if (success) {
              this.$message.success('删除sku成功!')
              this.getSkuList()
            } else {
              this.$message.error(message)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // sku列表图片ref处理
    handleRef(id) {
      this.uploadRefId = id
    },
    // 缩略图文件上传成功时候的钩子函数
    handleAvatarSuccess(res, file, fileList) {
      const { success, message, data } = res
      if (success) {
        var item = this.skuList.find(ele => ele.id === this.uploadRefId)
        item.pic = data.fileUrl
      } else {
        this.$message.error(message)
      }
    },
    // 在文件上传之前的钩子函数
    beforeAvatarUpload(file) {
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5
      var reg = /^image\/(jpe?g|png|webp|gif)$/

      const isImage = reg.test(file.type)
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      return isImage && isLt1dot5M
    },
    // 获取sku列表详情
    getSkuList() {
      getSkusByProductIdAPi(this.productId)
        .then(res => {
          const { message, success, data } = res
          if (success) {
            var items = data.items
            console.log('item=>>', items)
            // sku转化
            for (let i = 0; i < items.length; i++) {
              var item = items[i]
              var spData = JSON.parse(item.spData)
              spData.forEach(ele => {
                var skuItem = this.sku.find(el => el.name === ele.key)
                item[skuItem.type] = ele.value
              })
            }
            this.skuList = []
            for (let i = 0; i < items.length; i++) {
            //   Vue.set(this.skuList, i, items[i])
              this.$set(this.skuList, i, items[i])
            }
          } else {
            this.$message.error(message)
          }
        })
    },
    // 打开修改sku模态框
    showModal(id) {
      this.productId = id
      this.getSkuList()
      this.dialogVisible = true
    },
    // 点击右上角X
    closeModal() {
      this.dialogVisible = false
    },
    // 点击取消
    cancleUpdateSku() {
      this.dialogVisible = false
    },
    // 点击确定
    saveSku() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin:0 auto;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
